package com.bw.ivideo.test_fragment

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class BlankViewModel:ViewModel() {
    private val mRepository = BlankRepository()
    private val _uiState = MutableStateFlow<UiState>(UiState.Loading(false))
    val uiState: StateFlow<UiState> = _uiState

    fun loadLocalData() {
        viewModelScope.launch {
            _uiState.value = UiState.Loading(false)
            mRepository.getLocalData().collect{cached->
                if (cached != null) {
                    _uiState.value = UiState.Success(cached, fromCache = true)
                } else {
                    _uiState.value = UiState.Error(Exception("无缓存数据"), silent = true)
                }

            }
        }
    }

    fun loadRemoteData(silent: Boolean = false) {
        viewModelScope.launch {
            _uiState.value = UiState.Loading(silent)
            mRepository.getNetData().collect{data->
                mRepository.saveData(data)
                _uiState.value = UiState.Success(data, fromCache = false)
            }
        }
    }

    sealed class UiState {
        data class Loading(val silent: Boolean) : UiState()
        data class Success(val data: String, val fromCache: Boolean) : UiState()
        data class Error(val exception: Exception, val silent: Boolean) : UiState()
    }
}